"use strict";

const { AsyncLocalStorage } = require("node:async_hooks");
const http = require("node:http");
const { setImmediate } = require("node:timers");

const asyncLocalStorage = new AsyncLocalStorage();

/**
 * @param {string} msg
 */
function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : "-"}:`, msg);
}

let idSeq = 0;
http
  .createServer((req, res) => {
    asyncLocalStorage.run(idSeq++, () => {
      logWithId("start");
      // Imagine any chain of async operations here
      setImmediate(() => {
        logWithId("finish");
        res.end();
      });
    });
  })
  .listen(8080);

http.get("http://localhost:8080");
http.get("http://localhost:8080");
// Prints:
//   0: start
//   0: finish
//   1: start
//   1: finish
